package com.daohang361.imqq.protocol;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import com.daohang361.imqq.decoder.InterfaceDecoder;
import com.daohang361.imqq.encoder.InterfaceEncoder;
import com.daohang361.imqq.tool.*;
/**
 * encoder and decoder default loader
 * @author naner
 */
public class Myproper {
	/**
	 * 存放命令与类
	 */
private static Map<Integer,InterfaceEncoder> commandCoder=new HashMap<Integer,InterfaceEncoder>();
private static Map<Integer,InterfaceDecoder> commandDeCoder=new HashMap<Integer,InterfaceDecoder>();


static{
	initCoder();
	initDecoder();
}

	
	public static void initCoder(){
		 
		Map<Integer,String> coderList=new PH().getMap("encoder");
		Set<Integer> keys = coderList.keySet();
		for(Iterator<Integer> itr = keys.iterator(); itr.hasNext();){
			Integer key =  (Integer) itr.next();
			InterfaceEncoder encoder = getCoder(coderList.get(key));
			commandCoder.put(key, encoder);
		  }
	}
	private static void initDecoder() {
		 
		Map<Integer,String> coderList=new PH().getMap("decoder");
		Set<Integer> keys = coderList.keySet();
		for(Iterator<Integer> itr = keys.iterator(); itr.hasNext();){
			Integer key =  (Integer) itr.next();
			InterfaceDecoder decoder = getDecoder(coderList.get(key));
			commandDeCoder.put(key, decoder);
		  }
		
	}
	private static InterfaceDecoder getDecoder(String className) {
		InterfaceDecoder decoder=null;
		try {
			decoder = (InterfaceDecoder) Class.forName(className).newInstance();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return decoder;
	}
	private static InterfaceEncoder getCoder(String className) {
		InterfaceEncoder encoder=null;
		try {
			encoder = (InterfaceEncoder) Class.forName(className).newInstance();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return encoder;
	}
	/**
	 * 获取编码器
	 * @param command
	 * @return
	 */
	public static InterfaceEncoder getEncoder(int command)
	{
		return commandCoder.get(command);
	}
	/**
	 * 获取解析器
	 * @param command
	 * @return
	 */
	public static InterfaceDecoder getDecoder(int command)
	{
		return commandDeCoder.get(command);
	}
	
}
